#!/usr/bin/env python
#-*-encoding:utf-8-*-
'''
Created on 2015年3月17日

@author: chenyongbing
'''
import sys,os
#current_dir = os.path.dirname(__file__)
current_dir = os.path.split(os.path.realpath(__file__))[0]

import datetime

import numpy

sys.path.append(os.path.join(current_dir,'../'))
from base.PyMySQL import ConnectMySQL
from base.localConfig import baseLocalConfig
host = baseLocalConfig.mysqlConfig['datatuning']['host']
user = baseLocalConfig.mysqlConfig['datatuning']['user']
passwd = baseLocalConfig.mysqlConfig['datatuning']['passwd']
db = baseLocalConfig.mysqlConfig['datatuning']['db']


import logging

logger = logging.getLogger('base.similar_rssi_calculation')


class SimilarRssiCalculation(object):
    '''
    classdocs
    '''


    def __init__(self):
        '''
        Constructor
        '''
        self.myConnectMySQL = ConnectMySQL(host=host, user=user, password=passwd, db=db)
        
        
        
    def calculate_simlar_rssi(self,group,startTime=None,endTime=None,customer_avg_cnt=None,customer_min_rssi=-99,customer_max_rssi=0,walkby_list=[0,15,30,45,60,90,120]):
        for walkby in walkby_list:
            avgDatas = self.get_avg_count_from_database(group=group, startTime=startTime, endTime=endTime, walkby=walkby)
            
    
    
    
    def calculate_similarity_coefficient(self,expect_rssi=0,expect_flow=0,current_rssi=0,current_flow=0):
        pass
        coefficient = abs(numpy.log10(abs(expect_rssi))*numpy.log10(abs(expect_flow)) - numpy.log10(abs(current_rssi))*numpy.log10(abs(current_flow)))
        return coefficient
       
    def show_expect_rssi_order_by_similarity_coefficient(self,group,startTime=None,endTime=None,customer_weekday_avg_cnt=0,customer_weekend_avg_cnt=0,customer_min_rssi=-99,customer_max_rssi=0,walkby_list=[0,15,30,45,60,90,120]):
        datas = {}
        for walkby in walkby_list:
            weekday_avgDatas = self.get_avg_count_from_database(group=group, startTime=startTime, endTime=endTime, walkby=walkby,timeType='weekday')
            weekend_avgDatas = self.get_avg_count_from_database(group=group, startTime=startTime, endTime=endTime, walkby=walkby,timeType='weekend')
            #for rssi,flow in weekday_avgDatas.iteritems()
            for rssi in list(set(weekday_avgDatas.keys()+weekend_avgDatas.keys())):
                if rssi in weekday_avgDatas.keys():
                    weekday_flow = weekday_avgDatas[rssi]
                else:
                    weekday_flow = '-'
                if rssi in weekend_avgDatas.keys():
                    weekend_flow = weekend_avgDatas[rssi]
                else:
                    weekend_flow = '-'
                coefficientList = []
                for expect_rssi in range(customer_min_rssi,customer_max_rssi,2)+[customer_max_rssi]:
                    if weekday_flow!='-':
                        coefficient_weekday = self.calculate_similarity_coefficient(expect_rssi=expect_rssi, expect_flow=customer_weekday_avg_cnt, current_rssi=rssi, current_flow=weekday_flow)
                    else:
                        coefficient_weekday = 1
                    if weekend_flow!='-':
                        coefficient_weekend = self.calculate_similarity_coefficient(expect_rssi=expect_rssi, expect_flow=customer_weekend_avg_cnt, current_rssi=rssi, current_flow=weekend_flow)
                    else:
                        coefficient_weekend = 1
                    coefficient = coefficient_weekday*coefficient_weekend
                    coefficientList.append(coefficient)
                coefficientList.sort()
                if coefficientList[0] not in datas.keys():
                    datas[coefficientList[0]] = []
                datas[coefficientList[0]] = datas[coefficientList[0]] + ['%s:%s:%s:%s'%(walkby,rssi,weekday_flow,weekend_flow)]
        #return datas
        keys = datas.keys()
        keys.sort()
        ndatas = []
        for key in keys:
            
            for data in datas[key]:
                walkby,rssi,weekday_flow,weekend_flow = data.split(':')
                ndatas.append({'walkby':walkby,'rssi':rssi,'weekday_flow':weekday_flow,"weekend_flow":weekend_flow,'coefficient':key})
                
            
        return ndatas
    def get_avg_count_from_database(self,tab='group_count_by_rssi',group='',startTime=None,endTime=None,role_name='all_customer',walkby=60,expect_rssi=None,opening_time=None,timeType='all'):
        u'''
            timeType : all 全部  weekend 周末  weekday  工作日
        '''
        if int(walkby)==0:role_name = 'all_flow'
        query = 'select day,rssi,sum(visit_cnt) from %s where dgroup="%s"'%(tab,group)
        if startTime!=None and endTime!=None:
            query = query + ' and day between "%s" and "%s"'%(startTime,endTime)
        
        if timeType == 'weekday':
            query = query + ' and weekday(day) in (0,1,2,3,4)'
        elif timeType == 'weekend':
            query = query + ' and weekday(day) in (5,6)'
        
        if role_name == None:
            pass
        else:
            query = query + ' and role_name="%s" '%role_name
        
        if role_name == 'all_customer':
            query = query + ' and walkby="%s"'%walkby
        if expect_rssi!=None:
            query = query + ' and rssi="%s"'%expect_rssi
        if opening_time!=None and opening_time.keys() == ['opening_weekday','opening_weekend']:
            opening_weekday = opening_time['opening_weekday']
            opening_weekend = opening_time['opening_weekend']
            opening_weekday_hours = self.get_opening_hours(opening_weekday)
            opening_weekend_hours = self.get_opening_hours(opening_weekend)
            query_weekday = query + ' and weekday(day) in (0,1,2,3,4) and hour in (%s) group by day,rssi'%(','.join(opening_weekday_hours))
            query_weekend = query + ' and weekday(day) in (5,6) and hour in (%s) group by day,rssi'%(','.join(opening_weekend_hours))
            self.logger.debug(query_weekday)
            self.logger.debug(query_weekday)
            ret = list(self.myConnectMySQL.SelectAll(query_weekday)) + list(self.myConnectMySQL.SelectAll(query_weekend))
        else:
            query = query + ' group by day,rssi order by rssi,day'
            logger.debug(query)
            ret = self.myConnectMySQL.SelectAll(query)
       
        datas = {}
        for day,rssi,visit_cnt in ret:
            dayStr = day.strftime('%Y-%m-%d')
            if not datas.has_key(int(rssi)):
                datas[int(rssi)] = {}
            datas[int(rssi)][dayStr] = visit_cnt
            
            
        avgDatas = {}
        for rssi,ds in datas.iteritems():
            avgDatas[rssi] = int(round(sum(ds.values())/len(ds.keys()),0))
        
            
        if expect_rssi!=None:
            return avgDatas[rssi]
        return avgDatas
        
if __name__ == '__main__':
    mySimilarRssiCalculation = SimilarRssiCalculation()
    opening_time = None
    group = '32010134'
    startTime = '2014-09-20'
    endTime = '2014-10-20'
    role_name = 'all_customer'
    mySimilarRssiCalculation.show_expect_rssi_order_by_similarity_coefficient(group, startTime, endTime, customer_avg_cnt=26, customer_min_rssi=-60, customer_max_rssi=-50)
    print mySimilarRssiCalculation.calculate_similarity_coefficient(-90,172,-54,24)
#     datas =  mySimilarRssiCalculation.get_avg_count_from_database(group=group, startTime=startTime, endTime=endTime)
#     
#     for k,v in datas.iteritems():
#         print k,'\t',v
    
    
    